package com.dy.yunying.biz.service.ads.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dy.yunying.api.dto.AdmonitorRuleDto;
import com.dy.yunying.api.entity.AdmonitorRule;
import com.dy.yunying.api.entity.AdmonitorSituation;
import com.dy.yunying.api.entity.ParentGameDO;
import com.dy.yunying.api.enums.MonitorAdChannelType;
import com.dy.yunying.api.enums.MonitorAdItem;
import com.dy.yunying.api.enums.MonitorOperatorTypeEnum;
import com.dy.yunying.biz.dao.ads.AdmonitorRuleMapper;
import com.dy.yunying.biz.dao.manage.ext.ParentGameDOMapperExt;
import com.dy.yunying.biz.exception.YunyingException;
import com.dy.yunying.biz.service.ads.AdmonitorRuleService;
import com.dy.yunying.biz.service.ads.AdmonitorSituationService;
import com.pig4cloud.pig.admin.api.feign.RemoteUserService;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.util.SecurityUtils;

import com.pig4cloud.pig.api.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @ClassName AdmonitorRuleServiceImpl
 * @Description todo
 * @Author yangyh
 * @Time 2021/6/18 15:05
 * @Version 1.0
 **/
@Service
@Slf4j
public class AdmonitorRuleServiceImpl extends ServiceImpl<AdmonitorRuleMapper, AdmonitorRule> implements AdmonitorRuleService {

	@Autowired
	private AdmonitorSituationService admonitorSituationService;

	@Autowired
	private  RemoteUserService remoteUserService;
	@Autowired
	private ParentGameDOMapperExt parentGameDOMapperExt;

	@Override
	public R<IPage<AdmonitorRule>> queryAdmonitorRules(AdmonitorRuleDto admonitorRuleDto) {
		try {
			if (admonitorRuleDto.getReTime() != null) {
				Date createTimeEnd = admonitorRuleDto.getReTime();
				String format = new SimpleDateFormat("yyyy-MM-dd").format(createTimeEnd);
				admonitorRuleDto.setReTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(format + " 23:59:59"));
			}
			IPage<AdmonitorRule> admonitorRuleIPage = baseMapper.queryAdmonitorRules(admonitorRuleDto);
			List<AdmonitorRule> records = admonitorRuleIPage.getRecords();
			if(!CollectionUtils.isEmpty(records)){
				for (AdmonitorRule record : records) {
					Long monitorGameId = record.getMonitorGameId();
					if(monitorGameId==null || monitorGameId==0){
						record.setMonitorGame("所有");
					}else{
						ParentGameDO parentGameDO = parentGameDOMapperExt.selectByPrimaryKey(monitorGameId);
						if(parentGameDO!=null)record.setMonitorGame(parentGameDO.getGname());
					}
					Integer monitorChannelType = record.getMonitorChannelType();
					if(monitorChannelType!=null){
						MonitorAdChannelType byType = MonitorAdChannelType.getByType(monitorChannelType);
						if(byType!=null)record.setMonitorChannelTypeName(byType.getDesc());
					}
					String monitorAditem = record.getMonitorAditem();
					if(monitorAditem!=null){
						MonitorAdItem monitorAdItem = MonitorAdItem.valueOf(monitorAditem);
						record.setMonitorAditem(monitorAdItem.getDesc());
					}
				}

			}
			return R.ok(admonitorRuleIPage, "查询成功");
		} catch (YunyingException se) {
			return R.failed(se.getMessage());
		} catch (Exception e) {
			log.error("queryAdmonitorRules error:" + e.getMessage(), e);
			return R.failed("查询失败");
		}
	}



	@Override
	public R<AdmonitorRule> getAdmonitorRuleById(Integer id) {
		try {
			if (id == null || id == 0) throw new YunyingException("监控规则ID为空");
			AdmonitorRule admonitorRule = getById(id);
			if (admonitorRule == null) throw new YunyingException("监控规则ID不正确");
			List<AdmonitorSituation> list = admonitorSituationService.getByAdMonitorRuleId(id);
			admonitorRule.setAdmonitorSituations(list);
			return R.ok(admonitorRule, "查询成功");
		} catch (YunyingException se) {
			return R.failed(se.getMessage());
		} catch (Exception e) {
			log.error("getAdmonitorRuleById error:" + e.getMessage(), e);
			return R.failed("查询失败");
		}
	}

	@Override
	public R<Boolean> deleteAdmonitorRule(Integer id) {
		try {
			if (id == null || id == 0) throw new YunyingException("监控规则ID为空");
			AdmonitorRule admonitorRule = getById(id);
			if (admonitorRule == null) throw new YunyingException("监控规则ID不正确");
			admonitorSituationService.deleteByAdMonitorRuleId(id);
			admonitorRule.setUpdateBy(SecurityUtils.getUser().getId());
			admonitorRule.setUpdateTime(new Date());
			admonitorRule.setDelFlag(1);
			updateById(admonitorRule);
			return R.ok(true, "删除成功");
		} catch (YunyingException se) {
			return R.failed(se.getMessage());
		} catch (Exception e) {
			log.error("deleteAdmonitorRule error:" + e.getMessage(), e);
			return R.failed("删除失败");
		}
	}


	@Override
	public R<Boolean> updateAdmonitorRuleStatus(Integer id, Integer monitorStatus) {
		try {
			if (id == null || id == 0) throw new YunyingException("监控规则ID为空");
			if (monitorStatus == null) throw new YunyingException("监控状态为空");
			if (monitorStatus != 0) monitorStatus = 1;
			AdmonitorRule admonitorRule = getById(id);
			if (admonitorRule == null) throw new YunyingException("监控规则ID不正确");
			admonitorRule.setUpdateBy(SecurityUtils.getUser().getId());
			admonitorRule.setUpdateTime(new Date());
			admonitorRule.setMonitorStatus(monitorStatus);
			updateById(admonitorRule);
			return R.ok(true, "更新成功");
		} catch (YunyingException se) {
			return R.failed(se.getMessage());
		} catch (Exception e) {
			log.error("updateAdmonitorRuleStatus error:" + e.getMessage(), e);
			return R.failed("更新失败");
		}
	}


	@Override
	public R<Boolean> saveAdmonitorRule(AdmonitorRule admonitorRule) {
		try {
			validateAdmonitorRule(admonitorRule);
			admonitorRule.setCreateBy(SecurityUtils.getUser().getId());
			admonitorRule.setCreateTime(new Date());
			admonitorRule.setUpdateBy(SecurityUtils.getUser().getId());
			admonitorRule.setUpdateTime(new Date());
			admonitorRule.setDelFlag(0);
			if(admonitorRule.getMonitorStatus()==null) admonitorRule.setMonitorStatus(1);//没有的话，设置默认值开启

			AdmonitorRule monitorName = getOne(new QueryWrapper<AdmonitorRule>().eq("monitor_name", admonitorRule.getMonitorName()));
			if (monitorName != null) {
				throw new YunyingException("规则名称已存在【"+admonitorRule.getMonitorName()+"】");
			}
			save(admonitorRule);
			Integer id = admonitorRule.getId();
			if (id == null || id == 0) throw new YunyingException("保存监控规则失败");
			List<AdmonitorSituation> admonitorSituations = admonitorRule.getAdmonitorSituations();
			if (CollectionUtils.isEmpty(admonitorSituations)) throw new YunyingException("监控情形为空");
			for (AdmonitorSituation admonitorSituation : admonitorSituations) {
				admonitorSituation.setAdMonitorRuleId(id);
				admonitorSituationService.saveAdmonitorSituation(admonitorSituation);
			}
			return R.ok(true, "保存成功");
		} catch (YunyingException se) {
			return R.failed(se.getMessage());
		} catch (Exception e) {
			log.error("saveAdmonitorRule error:" + e.getMessage(), e);
			return R.failed("保存失败");
		}
	}

	@Override
	public R<Boolean> updateAdmonitorRule(AdmonitorRule admonitorRule) {
		try {
			validateAdmonitorRule(admonitorRule);
			if (admonitorRule.getId() == null || admonitorRule.getId() == 0) throw new YunyingException("监控规则ID为空");
			AdmonitorRule byId = getById(admonitorRule.getId());
			if(byId==null) throw new YunyingException("监控规则ID不正确");
			if(!byId.getMonitorName().equals(admonitorRule.getMonitorName())) {
				AdmonitorRule monitorName = getOne(new QueryWrapper<AdmonitorRule>().eq("monitor_name", admonitorRule.getMonitorName()));
				if (monitorName != null) {
					throw new YunyingException("规则名称已存在【" + admonitorRule.getMonitorName() + "】");
				}
			}
			admonitorRule.setUpdateBy(SecurityUtils.getUser().getId());
			admonitorRule.setUpdateTime(new Date());
			admonitorRule.setDelFlag(0);
			updateById(admonitorRule);
			List<AdmonitorSituation> admonitorSituations = admonitorRule.getAdmonitorSituations();
			if (CollectionUtils.isEmpty(admonitorSituations)) throw new YunyingException("监控情形为空");
			for (AdmonitorSituation admonitorSituation : admonitorSituations) {
				Integer id = admonitorSituation.getId();
				if (id == null || id == 0) {
					admonitorSituationService.saveAdmonitorSituation(admonitorSituation);
				} else {
					//将符合条件记录数清零
					admonitorSituation.setResultNo(0);
					admonitorSituationService.updateAdmonitorSituation(admonitorSituation);
				}
			}
			return R.ok(true, "保存成功");
		} catch (YunyingException se) {
			return R.failed(se.getMessage());
		} catch (Exception e) {
			log.error("updateAdmonitorRule error:" + e.getMessage(), e);
			return R.failed("保存失败");
		}
	}

	public void validateAdmonitorRule(AdmonitorRule admonitorRule) {
		if (admonitorRule == null) throw new YunyingException("请求参数为空");
		if (StringUtils.isBlank(admonitorRule.getMonitorName())) throw new YunyingException("监控规则名称为空");
		if (admonitorRule.getMonitorGameId()==null){
			admonitorRule.setMonitorGameId(0L);//不选代表所有
		}

		if (admonitorRule.getMonitorChannelType()==null){
			admonitorRule.setMonitorChannelType(0);//不选代表所有
		}


		if (StringUtils.isBlank(admonitorRule.getMonitorOperatorType())) throw new YunyingException("监控操作类型为空");
		MonitorOperatorTypeEnum monitorOperatorTypeEnum = null;
		try {
			monitorOperatorTypeEnum = MonitorOperatorTypeEnum.valueOf(admonitorRule.getMonitorOperatorType());
		} catch (Exception e) {
			throw new YunyingException("监控操作类型不正确");
		}
		if (MonitorOperatorTypeEnum.EMAIL.equals(monitorOperatorTypeEnum)) {
			if (StringUtils.isBlank(admonitorRule.getNotifytor()))throw new YunyingException("通知人员为空");

//			R<UserInfo> userinfoR = remoteUserService.findUserByUserId(admonitorRule.getNotifytor(), SecurityConstants.FROM_IN);
//			if(userinfoR.getData()==null)throw new YunyingException("通知人员ID不正确【"+admonitorRule.getNotifytor()+"】");
		}
		List<AdmonitorSituation> admonitorSituations = admonitorRule.getAdmonitorSituations();
		if (CollectionUtils.isEmpty(admonitorSituations)) throw new YunyingException("监控情形为空");
		for (AdmonitorSituation admonitorSituation : admonitorSituations) {
			admonitorSituationService.validateAdmonitorSituation(admonitorSituation);
		}
		if(StringUtils.isNotBlank(admonitorRule.getAdAccount())){
			if(admonitorRule.getScopeType()==null || admonitorRule.getScopeType()==0 )throw new YunyingException("监控范围类型为空");

		}


	}


}
